<!--
 * @Description:
 * @Author: 月间
 * @Date: 2024-11-14 21:09:55
 * @LastEditTime: 2025-10-10 20:37:01
 * @LastEditors:
-->
<script setup lang="tsx">
import { ref } from 'vue';
import type { Ref } from 'vue';
import { NButton, NPopconfirm, NTag, DataTableColumns, NDataTable } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { fetchGetDictList, fetchGetDictDataList, fetchDeleteDictData, fetchDeleteDictType } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { enableStatusRecord } from '@/constants/business';
import { RowData } from 'naive-ui/es/data-table/src/interface';
import TypeOperateDrawer, { type OperateType } from './modules/type_operate_drawer.vue';
import DataOperateDrawer from './modules/data_operate_drawer.vue';

const appStore = useAppStore();
const { bool: visible, setTrue: openModal } = useBoolean();

const { bool: visibleData, setTrue: openModalData } = useBoolean();

const columns_dict_data: DataTableColumns<Api.SystemManage.DictData> = [
  {
    title: '序号',
    key: 'index',
    minWidth: 60,
    align: 'center',
    render: (row, index) => index + 1,
  },
  {
    title: '标签',
    minWidth: 120,
    key: 'dictLabel',
    align: 'center',
  },
  {
    title: '值',
    minWidth: 80,
    key: 'dictValue',
    align: 'center',
  },
  {
    title: '排序',
    minWidth: 80,
    key: 'dictSort',
    align: 'center',
  },
  // 是否默认值
  {
    title: '是否默认值',
    minWidth: 100,
    align: 'center',
    key: 'isDefault',
    render: (row) => {
      if (row.isDefault === null) {
        return null;
      }

      const tagMap: Record<string, NaiveUI.ThemeColor> = {
        'Y': 'success',
        'N': 'warning'
      };


      return <NTag type={tagMap[row.isDefault]}>{row.isDefault === 'Y' ? '是' : '否'}</NTag>;
    },
  },
  {
    title: '状态',
    key: 'status',
    minWidth: 80,
    align: 'center',
    render: (row) => {
      if (row.status === null) {
        return null;
      }

      const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
        1: 'success',
        2: 'warning'
      };

      const label = $t(enableStatusRecord[row.status]);

      return <NTag type={tagMap[row.status]}>{label}</NTag>;
    },
  },
  {
    title: '描述',
    minWidth: 120,
    key: 'remark',
    align: 'center',
  },
  {
    key: 'operate',
    title: '操作',
    align: 'center',
    minWidth: 50,
    render(row) {
      return <div class="flex-center gap-8px">
        <NButton type="warning" ghost size="small" onClick={() => handleUpdateChild(row)}>
          {$t('common.edit')}
        </NButton>
        <NPopconfirm onPositiveClick={() => handleDeleteChild(row.id)}>
          {{
            default: () => $t('common.confirmDelete'),
            trigger: () => (
              <NButton type="error" ghost size="small">
                {$t('common.delete')}
              </NButton>
            )
          }}
        </NPopconfirm>
      </div>
    }
  }
];
const expandedList = ref<number[]>([]);
const dictTypeId = ref<number | null>(null);
// 编写异步请求后端
async function getDictData(dict_type_id: number) {
  console.log(expandedList.value, "expandedList");
  try {
    const { data } = await fetchGetDictDataList(dict_type_id);
    dictMap.value[dict_type_id] = data;
  } catch (error) {
    console.log(error);
  }
}
// 查询字典数据
async function getDictDataByTypeId() {
  if (!dictTypeId.value) return;
  await getDictData(dictTypeId.value);
}
const dictMap = ref<Record<number, Api.SystemManage.DictData[] | null>>({});
const { columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams } = useTable({
    apiFn: fetchGetDictList,
    apiParams: {
      current: 1,
      size: 10,
    },
    columns: () => [
      {
        type: 'selection',
        align: 'center',
        width: 48
      },
      {
        type: 'expand',
        renderExpand: (rowData) => {
          if (dictMap.value[rowData.id]) {
            return <NDataTable columns={columns_dict_data} data={dictMap.value[rowData.id] || []} />
          }
          getDictData(rowData.id);
          return <div>loading...</div>
        }
      },
      {
        key: 'id',
        title: $t('common.index'),
        width: 64,
        align: 'center'
      },
      {
        key: 'dictName',
        title: '名称',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'dictType',
        title: '类型',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'remark',
        title: '描述',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'status',
        title: '状态',
        align: 'center',
        minWidth: 120,
        render(row) {
          if (row.status === null) {
            return null;
          }

          const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
            1: 'success',
            2: 'warning'
          };

          const label = $t(enableStatusRecord[row.status]);

          return <NTag type={tagMap[row.status]}>{label}</NTag>;
        }
      },
      {
        key: 'operate',
        title: '操作',
        align: 'center',
        minWidth: 50,
        render(row) {
          return <div class="flex-center gap-8px">
            <NButton type="info" ghost size="small" onClick={() => handleAddChild(row.id)}>
              新增数据
            </NButton>
            <NButton type="warning" ghost size="small" onClick={() => handleEdit(row)}>
              {$t('common.edit')}
            </NButton>
          </div>
        }
      }
    ]
  }
  )

const { checkedRowKeys, onBatchDeleted, onDeleted } = useTableOperate(data, getData);

const operateType = ref<OperateType>('add');

async function handleBatchDelete() {
  // request
  console.log(checkedRowKeys.value);
  const { error } = await fetchDeleteDictType(checkedRowKeys.value);
  if (error) return;
  onBatchDeleted();
}

function handleDelete(id: number) {
  // request
  console.log(id);

  onDeleted();
}
const editingData: Ref<Api.SystemManage.DictType | null> = ref(null);
const editingDictData: Ref<Api.SystemManage.DictDataUpdate> = ref({});
function handleEdit(item: Api.SystemManage.DictType) {
  operateType.value = 'edit';
  editingData.value = { ...item };

  openModal();
}
function handleAdd() {
  operateType.value = 'add';
  editingData.value = null;

  openModal();
}

// // 新增子部门
function handleAddChild(id: number) {
  operateType.value = 'add';
  if (id) {
    editingDictData.value.dictTypeId = id
    dictTypeId.value = id
    openModalData();
  }
}
function handleUpdateChild(item: Api.SystemManage.DictData) {
  operateType.value = 'edit';
  editingDictData.value = { ...item };
  dictTypeId.value = item.dictTypeId;
  openModalData();
}
async function handleDeleteChild(id: number) {
  // request
  const { error } = await fetchDeleteDictData(id);
  if (error) return;
  console.log(id);
  await getDictData(id)
  window.$message?.success($t('common.deleteSuccess'));
  // onDeleted();
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title="字典管理" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation v-model:columns="columnChecks" :loading="loading" @refresh="getData">
          <template #prefix>
            <NButton size="small" ghost type="primary" @click="handleAdd">
              <template #icon>
                <icon-ic-round-plus class="text-icon" />
              </template>
              {{ $t('common.add') }}
            </NButton>
            <NPopconfirm @positive-click="handleBatchDelete">
              <template #trigger>
                <NButton size="small" ghost type="error" :disabled="checkedRowKeys.length === 0">
                  <template #icon>
                    <icon-ic-round-delete class="text-icon" />
                  </template>
                  {{ $t('common.batchDelete') }}
                </NButton>
              </template>
              {{ $t('common.confirmDelete') }}
            </NPopconfirm>
          </template>
        </TableHeaderOperation>
      </template>
      <NDataTable v-model:checked-row-keys="checkedRowKeys" :columns="columns" :data="data" size="small"
        :flex-height="!appStore.isMobile" :scroll-x="702" :loading="loading" remote :row-key="row => row.id"
        :pagination="mobilePagination" class="sm:h-full" />
      <TypeOperateDrawer v-model:visible="visible" :operate-type="operateType" :row-data="editingData"
        @submitted="getDataByPage" />
      <DataOperateDrawer v-model:visible="visibleData" :operate-type="operateType" :row-data="editingDictData"
        @submitted="getDictDataByTypeId" />
    </NCard>
  </div>
</template>

<style scoped></style>
